package com.wss.common.utils;

import com.wss.common.base.BaseApplication;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.webengine.ResourceResponse;
import ohos.app.Context;
import ohos.bundle.BundleInfo;
import ohos.bundle.IBundleManager;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Describe：工具类
 * Created by 吴天强 on 2018/10/15.
 */
public class Utils {

    /**
     * 读取 rawfile下的文件
     *
     * @param context  context
     * @param fileName fileName (例如：“entry/resources/rawfile/test.txt”)
     * @return String
     */
    public static String getAssetFileData(@NotNull Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        RawFileEntry rawFileEntry = context.getResourceManager()
                .getRawFileEntry(fileName);

        if (rawFileEntry != null) {
            try {
                String mimeType = URLConnection.guessContentTypeFromName(fileName);
                Resource resource = rawFileEntry.openRawFile();
                ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                BufferedReader bf = new BufferedReader(new InputStreamReader(response.getData()));
                String line;
                while ((line = bf.readLine()) != null) {
                    stringBuilder.append(line);
                }
                bf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }

    /**
     * 验证邮箱
     *
     * @param email email字符串
     * @return 如果是邮件地址 返回 true
     */
    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 判断是否为纯数字
     *
     * @param str str
     * @return boolean
     */
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    /**
     * 判断是否为电话，只校验位数
     *
     * @param str str
     * @return boolean
     */
    public static boolean isPhone(String str) {
        return ValidUtils.isValid(str) && str.length() == 11;
    }

    /**
     * 获取APP包名
     *
     * @return String
     */
    public static String getBundleName() {
        return BaseApplication.i().getBundleName();
    }

    /**
     * 获取APP 版本名称
     *
     * @return String
     */
    public static String getVersionName() {

        IBundleManager bundleManager = BaseApplication.i().getBundleManager();
        String bundleName = BaseApplication.i().getBundleName();
        try {
            BundleInfo bundleInfo = bundleManager.getBundleInfo(bundleName, 0x00000001);
            return bundleInfo.getVersionName();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取APP 版本号
     *
     * @return Integer
     */
    public static Integer getVersionCode() {
        IBundleManager bundleManager = BaseApplication.i().getBundleManager();
        String bundleName = BaseApplication.i().getBundleName();
        try {
            BundleInfo bundleInfo = bundleManager.getBundleInfo(bundleName, 0x00000001);
            return bundleInfo.getVersionCode();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 设置TextView的背景色
     *
     * @param textView textView
     * @param color    颜色
     */
    public static void setTextViewDrawable(@NotNull Text textView, int color) {
        setTextViewDrawable(textView, color, 4);
    }

    /**
     * 设置TextView的背景色
     *
     * @param textView textView
     * @param color    颜色
     * @param radius   圆角角度
     */
    public static void setTextViewDrawable(@NotNull Text textView, int color, float radius) {
        ShapeElement drawable = new ShapeElement();
        drawable.setCornerRadius(radius);
        drawable.setRgbColor(new RgbColor(color));
        textView.setBackground(drawable);
    }

    /**
     * 跳转浏览器
     */
    public static void toSystemBrowser(Context context, String url) {
        //应用内下载失败 跳转浏览器下载

        Uri contentUrl = Uri.parse(url);
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withUri(contentUrl)
                .withAction("android.intent.action.VIEW")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setUriAndType(contentUrl, null);
        intent.setOperation(operation);
        context.startAbility(intent, 0);
    }




    /**
     * 电话号码中间替换成*
     *
     * @param phone 原电话
     * @return 替换后的电话
     */
    @Contract("_ -> param1")
    public static String replacePhone(String phone) {
        if (!isPhone(phone)) {
            return phone;
        }
        String replace = phone.substring(3, 7);
        return phone.replace(replace, "****");
    }

    /**
     * 把等于null的字符串转成“”
     *
     * @param text 原字符串
     * @return 转换后字符串
     */
    public static String checkText(String text) {
        if (!ValidUtils.isValid(text)) {
            return "";
        }
        return text;
    }
}
